#include "user_manager.h"

UserManager::UserManager(std::string filename)
    : fileManager(filename) {
    this->loadUsers();
}

UserManager::~UserManager() {
    for (User* user : users) {
        delete user;
    }
    users.clear();
}

void UserManager::createUser(User* user) {
    users.push_back(user);
    fileManager.saveUsers(users);
}

User* UserManager::readUser(int id) {
    for (User* user : users) {
        if (user->getId() == id) {
            return user;
        }
    }
    return nullptr;
}

void UserManager::updateUser(int id, std::string newName, std::string newPassword) {
    for (User* user : users) {
        if (user->getId() == id) {
            user->setName(newName);
            user->setPassword(newPassword);
            fileManager.saveUsers(users);
            return;
        }
    }
    std::cerr << "User with ID " << id << " not found." << std::endl;
}

void UserManager::deleteUser(int id) {
    for (auto it = users.begin(); it != users.end(); ++it) {
        if ((*it)->getId() == id) {
            delete *it;
            users.erase(it);
            fileManager.saveUsers(users);
            return;
        }
    }
    std::cerr << "User with ID " << id << " not found." << std::endl;
}

void UserManager::displayAllUsers() {
    for (User* user : users) {
        user->displayInfo();
    }
}

void UserManager::loadUsers() {
    users = fileManager.loadUsers();
}    